package com.leoman.work.controller;

import com.leoman.adsindex.entity.AdsIndex;
import com.leoman.adsindex.service.AdsIndexService;
import com.leoman.banner.entity.Banner;
import com.leoman.banner.service.BannerService;
import com.leoman.barrage.entity.Barrage;
import com.leoman.barrage.service.BarrageService;
import com.leoman.category.entity.Category;
import com.leoman.category.service.CategoryService;
import com.leoman.comment.service.WorkCommentService;
import com.leoman.common.controller.common.GenericEntityController;
import com.leoman.common.factory.DataTableFactory;
import com.leoman.entity.Constant;
import com.leoman.exception.GeneralExceptionHandler;
import com.leoman.floatwin.entity.FloatWin;
import com.leoman.floatwin.service.FloatWinService;
import com.leoman.sensitivewords.service.SensitiveWordsService;
import com.leoman.sohuapi.api.SohuApi;
import com.leoman.sohuapi.entity.AlbumFromSohu;
import com.leoman.sohuapi.entity.VideoDetailFromSohu;
import com.leoman.sohuapi.entity.VideoFromSohu;
import com.leoman.sohuapi.entity.VideoSubFromSohu;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.service.UserService;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.WebUtil;
import com.leoman.welfare.entity.Welfare;
import com.leoman.welfare.service.WelfareService;
import com.leoman.work.entity.*;
import com.leoman.work.service.WorkCreatorService;
import com.leoman.work.service.WorkService;
import com.leoman.work.service.WorkSurroundService;
import com.leoman.work.service.WorkVideoService;
import com.leoman.work.service.impl.WorkServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by 蔡琦 on 2016/6/15 0015.
 */
@Controller
@RequestMapping(value = "admin/work")
public class WorkController extends GenericEntityController<Work, Work, WorkServiceImpl> {

    @Autowired
    private WorkService workService;

    @Autowired
    private WorkVideoService workVideoService;

    @Autowired
    private UserService userService;

    @Autowired
    private WorkSurroundService workSurroundService;

    @Autowired
    private WorkCreatorService workCreatorService;

    @Autowired
    private BarrageService barrageService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WelfareService welfareService;

    @Autowired
    private WorkCommentService workCommentService;

    @Autowired
    private SensitiveWordsService sensitiveWordsService;

    @Autowired
    private BannerService bannerService;

    @Autowired
    private AdsIndexService adsIndexService;

    @Autowired
    private FloatWinService floatWinService;


    /**
     * 列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/index")
    public String index() {
        return "work/list";
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = "/list")
    public void list(HttpServletResponse response,
                     String name,
                     Long type,
                     Integer status,
                     Integer draw,
                     Integer start,
                     Integer length) {
        try {
            List<WorkVideo> workVideoList;
            int pageNum = getPageNum(start, length);

            Page<Work> page = workService.page(name, type, status, Constant.CATEGORY_TYPE_004, pageNum, length);
            //List<Barrage> barrageList = null;
            for (Work work : page.getContent()) {

                // 查询最新视频续集
                workVideoList = workVideoService.findByWorkId(work.getId());
                if (workVideoList.size() != 0) {
                    work.setWorkVideo(workVideoList.get(workVideoList.size()-1));
                }

                /*for (WorkVideo workVideo : workVideoList) {
                    barrageList = barrageService.findByTypeAndWorkId(workVideo.getId(), 0);
                    work.setBarrageNum(work.getBarrageNum() + (barrageList != null? barrageList.size() : 0));
                }*/
            }
            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Integer add(Long id, Long categoryId) {

        Work work = workService.findBySoHuId(id);

        AlbumFromSohu albumFromSohu = SohuApi.apiFromSohuAlibum(id);
        if (work == null) {
            work = new Work();
            work.setCreateDate(System.currentTimeMillis());
        }
        work.setName(albumFromSohu.getAlbum_name());
        work.setCover(albumFromSohu.getHor_high_pic());
        work.setSeriesCount(albumFromSohu.getTotal_video_count() != null ? albumFromSohu.getTotal_video_count():0);
        work.setDescription(albumFromSohu.getAlbum_desc());
        work.setPlayNum(albumFromSohu.getPlay_count()  != null ? albumFromSohu.getPlay_count():0);
        work.setAlbumId(id);
        //work.setUpdateCount(albumFromSohu.getPlay_count() != null ? albumFromSohu.getPlay_count() : 0);
        work.setUpdateCount(albumFromSohu.getLatest_video_count());
        work.setCategory(categoryService.queryByPK(categoryId));
        if (albumFromSohu.getTotal_video_count().equals(albumFromSohu.getLatest_video_count())) {
            work.setIsEnd(1);
        }
        work.setStatus(0);
        workService.update(work);

        return 1;
    }

    /**
     * 编辑
     *
     */
    @RequestMapping(value = "/edit")
    public String edit(Long workId, Model model) {
        try {
            //Map<String, Object> map = new HashMap<String, Object>();
            //List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

            Work work = workService.queryByPK(workId);

            List<WorkCreator> workCreatorList = workCreatorService.findWorkId(workId);

            List<WorkSurround> workSurroundList = workSurroundService.findByWorkId(workId);

            /*List<UserInfo> creatorList = userService.findByStatus(1);
            model.addAttribute("creatorList", creatorList);*/

            model.addAttribute("work", work);
            model.addAttribute("workCreatorList", workCreatorList);
            model.addAttribute("workSurroundList", workSurroundList);

            StringBuilder sb = new StringBuilder("");
            for (WorkCreator workCreator : workCreatorList) {
                sb.append(workCreator.getUserInfo().getId() + ",");
            }

            model.addAttribute("tempCreatorIds", sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "work/add";
    }

    /**
     * 剧集列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/indexVideo")
    public String indexVideo(Long workId, Model model) {

        Work work = workService.queryByPK(workId);

        List<WorkVideo> workVideoList = workVideoService.findByWorkId(work.getId());
        int page = workVideoList.size()/10;

        //AlbumFromSohu albumFromSohu = SohuApi.apiFromSohuAlibum(work.getAlbumId());
        WorkVideo workVideo;
        VideoDetailFromSohu videoDetailFromSohu;
        VideoSubFromSohu videoSubFromSohu = SohuApi.apiFromSohuVideoList(work.getAlbumId(), page + 1, 10);
        if (videoSubFromSohu.getList() != null) {
            for (VideoFromSohu videoFromSohu : videoSubFromSohu.getList()) {
                if (videoFromSohu.getVideo_order() > workVideoList.size()) {

                    videoDetailFromSohu = SohuApi.apiFromSohuVideoDetail(videoFromSohu.getVid(),work.getAlbumId());
                    workVideo = new WorkVideo();
                    workVideo.setName(videoFromSohu.getVideo_name());
                    workVideo.setWork(work);
                    workVideo.setLength(videoFromSohu.getTime_length());
                    workVideo.setSeries(videoFromSohu.getVideo_order());
                    workVideo.setLinkUrl(videoFromSohu.getUrl_html5());
                    workVideo.setVid(videoFromSohu.getVid());
                    workVideo.setSite(videoDetailFromSohu.getSite());
                    workVideoService.save(workVideo);
                }
                if (videoFromSohu.getVideo_order() <= workVideoList.size()) {
                    for (WorkVideo workVideo1 : workVideoList) {
                        workVideo = workVideo1;
                        workVideo.setBarrageNum(workVideo1.getBarrageNum());
                        //workVideo.setPlayNum(workVideo.getPlayNum());
                        workVideoService.save(workVideo);
                    }
                }
            }
        }

        model.addAttribute("work", work);

        return "work/videoList";
    }

    /**
     * 查询剧集列表
     */
    @RequestMapping(value = "/videoList")
    public void videoList(HttpServletResponse response,
                          Long workId,
                          Integer draw,
                          Integer start,
                          Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<WorkVideo> page = workVideoService.page(workId, pageNum, length);
            List<Barrage> barrageList = null;
            for (WorkVideo workVideo: page.getContent()) {
                barrageList = barrageService.findByTypeAndWorkId(workVideo.getId(), 0);
                workVideo.setBarrageNum(barrageList != null? barrageList.size() : 0);
            }

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 查询主创列表
     */
    @RequestMapping(value = "/creatorList")
    @ResponseBody
    public List<UserInfo> creatorList() {

        return userService.findByStatus();
    }

    /**
     * 查询视频主创列表
     */
    @RequestMapping(value = "/videoCreatorList")
    @ResponseBody
    public List<UserInfo> videoCreatorList(Long workId) {

        List<WorkCreator> videoCreatorList = workCreatorService.findWorkId(workId);
        List<UserInfo> creatorList = new ArrayList<>();
        for (WorkCreator workCreator : videoCreatorList) {
            creatorList.add(workCreator.getUserInfo());
        }
        return creatorList;
    }

    /**
     * 查询类型列表
     */
    @RequestMapping(value = "/typeList")
    @ResponseBody
    public List<Category> typeList() {

        return categoryService.findType(Constant.CATEGORY_TYPE_004);
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Integer save(Long id,
                        String name,
                        Integer seriesCount,
                        Long category,
                        String description,
                        String[] creator,
                        String[] type,
                        String[] welfareList,
                        String[] types,
                        String[] welfareLists,
                        MultipartRequest multipartRequest) throws IOException {

        workSurroundService.saveAll(id, name, seriesCount, category, description, creator, type, welfareList,
                types, welfareLists, multipartRequest);

        return 1;
    }

    /**
     * 新增主创弹幕
     */
    @RequestMapping(value = "/addBarrage")
    @ResponseBody
    public Integer addBarrage(Integer time, String detail, Long barrageId, Long workVideoId, Long creatorId) throws UnsupportedEncodingException {

        //String msg = request.getParameter("time");
        //String msg2 = request.getParameter("detail");

        //String str = new String(msg.getBytes("ISO-8859-1"), "UTF-8");
        //String str2 = new String(msg2.getBytes("ISO-8859-1"), "UTF-8");

        Barrage barrage;
        if (barrageId == null) {
            barrage = new Barrage();
        } else {
            barrage = barrageService.queryByPK(barrageId);
        }

        //barrage.setUserLogin(userService.queryByPK(creatorId).getUserLogin());
        barrage.setUserInfo(userService.queryByPK(creatorId));
        detail = sensitiveWordsService.replaceWord(detail);
        barrage.setContent(detail);
        barrage.setType(0);
        barrage.setTime(time);
        barrage.setPraise(0L);
        barrage.setWorkId(workVideoId);
        barrage.setName(workVideoService.queryByPK(workVideoId).getWork().getName());
        barrageService.save(barrage);

        WorkVideo workVideo = workVideoService.queryByPK(workVideoId);
        workVideo.setBarrageNum(workVideo.getBarrageNum() + 1);
        workVideoService.save(workVideo);

        Work work = workVideoService.queryByPK(workVideoId).getWork();
        work.setBarrageNum(work.getBarrageNum() + 1);
        workService.update(work);
        return 1;

    }

    /**
     * 主创弹幕列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/indexBarrage")
    public String indexBarrage(Long workId, Model model) {

        WorkVideo workVideo = workVideoService.queryByPK(workId);
        //WorkCreator workCreator = workCreatorService.findByWorkId(workVideo.getWork().getId());

        model.addAttribute("workVideo", workVideo);
        //model.addAttribute("workCreator", workCreator);

        return "work/barrageList";
    }

    /**
     * 查询弹幕列表
     */
    @RequestMapping(value = "/barrageList")
    public void barrageList(HttpServletResponse response,
                            Long workId,
                            Integer draw,
                            Integer start,
                            Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<Barrage> page = barrageService.page(workId, pageNum, length);

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 批量删除视频
     */
    @RequestMapping(value = "/deleteBatch")
    @ResponseBody
    public Integer deleteBatch(String ids) {
        Long[] arrayId = JsonUtil.json2Obj(ids, Long[].class);
        List<WorkComment> workCommentList;
        List<Barrage> barrageList;
        for (Long id : arrayId) {

            // 是否链接到广告banner
            List<Banner> bannerList = bannerService.findByTypeAndCategoryId(Constant.POSITION_001, id);
            if (bannerList.size() != 0) {
                return 2;
            }

            // 是否链接到首页推荐
            List<AdsIndex> adsIndexList = adsIndexService.findByTypeAndCategoryId(Constant.POSITION_001, id);
            if (adsIndexList.size() != 0) {
                return 2;
            }

            // 是否链接到浮窗广告
            List<FloatWin> floatWinList = floatWinService.findByTypeAndCategoryId(Constant.POSITION_001, id);
            if (floatWinList.size() != 0) {
                return 2;
            }

            // 删除该视频的周边购买
            List<WorkSurround> workSurroundList = workSurroundService.findByWorkId(id);
            for (WorkSurround workSurround : workSurroundList) {
                workSurroundService.delete(workSurround);
            }

            List<WorkVideo> workVideoList = workVideoService.findByWorkId(id);
            for (WorkVideo workVideo : workVideoList) {

                // 查询视频续集评论
                workCommentList = workCommentService.findList(workVideo.getId(), Constant.CATEGORY_TYPE_004, Constant.COMMENT_TYPE_DEFAULT, Constant.COMMENT_PRAISE_ISDETAIL_YES);
                for (WorkComment workComment : workCommentList) {
                    workCommentService.deleteComment(workComment.getId());
                }

                // 查询视频续集弹幕
                barrageList = barrageService.findByTypeAndWorkId(workVideo.getId(), 0);
                for (Barrage barrage : barrageList) {
                    barrageService.delete(barrage);
                }
            }

            // 查询视频弹幕
            workCommentList = workCommentService.findList(id, Constant.CATEGORY_TYPE_004, Constant.COMMENT_TYPE_DEFAULT, Constant.COMMENT_PRAISE_ISDETAIL_NO);
            for (WorkComment workComment : workCommentList) {
                workCommentService.deleteComment(workComment.getId());
            }


            workService.deleteWork(id);

        }

        return 1;
    }

    /**
     * 删除视频主创
     */
    @RequestMapping(value = "/deleteCreator")
    @ResponseBody
    public Integer deleteCreator(Long workId) {

        WorkCreator workCreator = workCreatorService.queryByPK(workId);
        workCreatorService.delete(workCreator);

        return 1;
    }

    /**
     * 删除作品周边购买
     */
    @RequestMapping(value = "/deleteSurround")
    @ResponseBody
    public Integer deleteSurround(Long id) {

        WorkSurround workSurround = workSurroundService.queryByPK(id);
        workSurroundService.delete(workSurround);

        return 1;
    }

    /**
     * 根据类型查找福利社列表
     *
     * @return list
     */
    @RequestMapping(value = "/loadWelfare")
    @ResponseBody
    public List<Welfare> loadWelfare(Integer categoryId) {

        return welfareService.findByType(categoryId);
    }
}
